<?php


namespace App\Service\Store;


use App\Constants\Agent;
use App\Dao\AgentDao;
use App\Dao\BusinessDao;
use App\Dao\LocationDao;
use App\Dao\PartServantConfigDao;
use App\Dao\UserDao;
use App\Service\Service;
use Hyperf\Di\Annotation\Inject;

/**
 * 合伙人服务
 * @author 陈奕文
 * @package App\Service\Store
 */
class PartnerService extends Service
{

    /**
     * 代理Dao
     * @Inject()
     * @var AgentDao 
     */
    public $agent_dao;

    /**
     * 配置Dao
     * @Inject()
     * @var PartServantConfigDao
     */
    public $part_servant_config_dao;

    /**
     * 位置Dao
     * @Inject()
     * @var LocationDao
     */
    public $location_dao;

    /**
     * 用户Dao
     * @Inject()
     * @var UserDao
     */
    public $user_dao;

    /**
     * 商家Dao
     * @Inject()
     * @var BusinessDao
     */
    public $business_dao;

    /**
     * 市场合伙人搜索
     * @param array $params
     * @return mixed
     */
    public function getMarketer(array $params)
    {
        $map = [];
        isset($params['start_time']) && !isset($params['end_time']) && !empty($params['start_time']) && $map['created_at'] = ['>=', strtotime($params['start_time'])]; // 申请开始时间
        isset($params['end_time']) &&  !isset($params['start_time'])&& !empty($params['end_time'])  && $map['created_at'] = ['<=', strtotime($params['end_time'])]; // 申请结束时间

        isset($params['end_time']) &&  isset($params['start_time'])
        && !empty($params['end_time']) && !empty($params['start_time'])
        && $map['between_field'] = ['created_at' =>[strtotime($params['start_time']), strtotime($params['end_time'])]]; // 有申请开始和结束时间

        isset($params['contact_name'])  && !empty($params['contact_name']) && $map['contact_name'] = ['like', "%{$params['contact_name']}%"]; // 联系人
        isset($params['link_phone'])  && !empty($params['link_phone']) && $map['link_phone'] = ['like', "%{$params['link_phone']}%"]; // 联系电话
        isset($params['address'])  && !empty($params['address']) && $map['address'] = ['like', "%{$params['address']}%"]; // 联系地址
        isset($params['corporate_name'])  && !empty($params['corporate_name']) && $map['corporate_name'] = ['like', "%{$params['corporate_name']}%"]; // 公司名称

        isset($params['status']) && $map['status'] = (int)$params['status']; // 状态: 0=未审核 1=已审核 2已停用 3已拒绝

        $map['identity'] = 4; // 合伙人

        $select = ['id', 'status', 'identity', 'name', 'phone', 'link_phone', 'address', 'corporate_name' , 'contact_name','refuse_reason', 'created_at'];
        $sort = 'created_at desc';
        $page_size = 10;
          // 合伙人代理
        $partner_list =  $this->agent_dao->getAgentsByMap($map, $sort, $select, $page_size)->toArray();

        $partner_list['data'] = $this->joinMarketerData($partner_list['data']);

        return $partner_list;

    }

    /**
     * 拼接数据
     * @param array $partner_list
     * @return array
     */
    public function joinMarketerData(array $partner_list)
    {
        foreach ($partner_list as &$item) {
            $item['status'] = (int)$item['status'];
            $item['status_text'] = Agent::STATUS_LIST[$item['status']]??''; // 状态名称
            $item['create_time'] = date("Y.m.d", (int)$item['created_at']); // 创建时间
        }

        return $partner_list;
    }

    /**
     * 合伙人详情
     * @param int $id
     * @return mixed
     */
    public function marketerDetail(int $id)
    {
        $partner = $this->agent_dao->first($id);
        !$partner && $this->error("该代理商不存在");

        $partner = $partner->toArray();

        $invite_partner = $this->agent_dao->first((int)$partner['inviter_id']); // 邀请人信息 (分公司)
        !$invite_partner && $this->error("合伙人没有隶属分公司");

        $partner['company_legal_name'] = $invite_partner['settle_name']; // 法人名称

        $partner['company_business_license'] = $invite_partner['business_license']; // 公司营业执照

        $money_values = $this->part_servant_config_dao->many([
            'name' =>['in',['partner_area_money', 'partner_city_money', 'partner_channel_money']]
        ], ['name', 'value'])->pluck('value', 'name')->toArray(); // 获取分佣比率配置信息

        empty($partner['area_agent_money']) && $partner['area_agent_money'] = $money_values['partner_area_money']; // 区代理金额返佣
        empty($partner['city_agent_money']) && $partner['city_agent_money'] = $money_values['partner_city_money']; // 市代理金额返佣
        empty($partner['channel_agent_money']) && $partner['channel_agent_money'] = $money_values['partner_channel_money']; // 渠道商金额返佣
        $partner['status_text'] = Agent::STATUS_LIST[$partner['status']]??''; // 状态名称
        $partner['create_time'] = date('Y.m.d',(int)$partner['created_at']); // 创建时间

        return $partner;

    }

    /**
     * 代理搜索
     * @param array $params
     * @return mixed
     */
    public function agentSearch(array $params)
    {
        $map = [];
        isset($params['start_time']) && !isset($params['end_time']) && !empty($params['start_time']) && $map['created_at'] = ['>=', strtotime($params['start_time'])]; // 申请开始时间
        isset($params['end_time']) &&  !isset($params['start_time'])&& !empty($params['end_time'])  && $map['created_at'] = ['<=', strtotime($params['end_time'])]; // 申请结束时间

        isset($params['end_time']) &&  isset($params['start_time'])
        && !empty($params['end_time']) && !empty($params['start_time'])
        && $map['between_field'] = ['created_at' =>[strtotime($params['start_time']), strtotime($params['end_time'])]]; // 有申请开始和结束时间

        isset($params['name'])  && !empty($params['name']) && $map['name'] = ['like', "%{$params['name']}%"]; // 姓名
        isset($params['phone'])  && !empty($params['phone']) && $map['phone'] = ['like', "%{$params['phone']}%"]; // 账号

        isset($params['address'])  && !empty($params['address']) && $map['address'] = ['like', "%{$params['address']}%"]; // 联系地址

        isset($params['search']) && !empty($params['search']) // 搜索
        && $map['or_field'] = [
            'contact_name' => ['like', "%{$params['search']}%"], // 联系人
            'link_phone' => ['like', "%{$params['search']}%"], // 联系方式
        ];

        isset($params['identity'])  && !empty($params['identity']) && $map['identity'] = (int)$params['identity']; // 代理商角色
        isset($params['inviter_id']) && !empty($params['inviter_id']) && $map['inviter_id'] = (int)$params['inviter_id']; // 上级代理商ID
        $sort = 'created_at desc';
        $select = ['id', 'created_at', 'identity', 'corporate_name', 'phone', 'contact_name', 'link_phone', 'name', 'inviter_id', 'status', 'address', 'location_id'];

        $page_size = 10;
        $agent_list = $this->agent_dao->getAgentsByMap($map, $sort, $select, $page_size)->toArray();

        $agent_list['data'] = $this->joinAgentData($agent_list['data'], $map);

        return $agent_list;

    }

    /**
     * 加入数据
     * @param array $agent_list
     * @param $map
     * @return array
     */
    public function joinAgentData(array $agent_list, $map)
    {
        $invite_ids = array_unique(array_column($agent_list, 'inviter_id')) ;
        $agents = $this->agent_dao->getAgentsByMap([
            'id' => ['in', $invite_ids],
        ], null, ['id', 'identity', 'location_id', 'name', 'corporate_name','inviter_id']);
        $parent_agent_names = $agents->pluck('name', 'id')->toArray(); // 名称
        $parent_agent_identities = $agents->pluck('identity', 'id')->toArray(); // 身份角色
        $parent_agent_inviters = $agents->pluck('inviter_id', 'id')->toArray(); // 邀请人ID
        $parent_agent_corporate = $agents->pluck('corporate_name', 'id')->toArray(); // 公司
        foreach ($agent_list as &$item) {
            $item['parent_name'] = $parent_agent_names[$item['inviter_id']]??''; // 上级名称
            $item['parent_identity'] = $parent_agent_identities[$item['inviter_id']]??null; // 上级角色
            $item['status_text'] = Agent::STATUS_LIST[$item['status']]; // 状态名称
            $item['create_time'] = date("Y.m.d",(int)$item['created_at']); // 创建时间
            $city_agent = ''; // 归属市代理
            $market_partner = ''; // 归属市场合伙人
            $branch_company = ''; // 归属分公司

            if ($item['identity'] == 1 ) { // 如果是区代理身份
                if ($item['parent_identity'] == 2) { // 上级为市代理
                    $city_agent .= $item['parent_name']; // 市代名称

                    $parent_inviter_id = $parent_agent_inviters[$item['inviter_id']]??null;
                    if ($parent_inviter_id) { // 存在合伙人或者分公司
                            $parent = $this->agent_dao->map([
                                'id' => $parent_inviter_id
                            ], false);
                            if ($parent) {
                                $parent = $parent->toArray();
                                if ($parent['identity'] == 3) { // 分公司
                                    $branch_company .= $parent['name'];
                                } else { // 市场合伙人
                                    $market_partner .= $parent['name'];
                                    $branch_company .= $parent['corporate_name'];
                                }
                            }
                    }
                }
                if ($item['parent_identity'] == 3) { // 上级为分公司
                    $branch_company .= $item['parent_name']; // 分公司名称

                    $location = $this->location_dao->getLocationByPid([
                        'pid' => $item['location_id'],
                    ])->toArray();

                    $up_city_agent = $this->agent_dao->map([
                        'location_id' => $location['level'],
                        'identity' => 2
                    ]);
                   if ($up_city_agent) { // 上层市代存在
                       $up_city_agent = $up_city_agent->toArray();
                       $city_agent .= $up_city_agent['name']; // 市代理名称

                       $super = $this->agent_dao->map([
                           'id' => $up_city_agent['inviter_id'],
                       ]); // 最后一步，最高一层 合伙人或者分公司

                       if ($super && $super = $super->toArray() && $super['id'] != $item['inviter_id']) { // 市代存在且市代的邀请人存在
                           $super['identity'] == 3 && $branch_company .= " ". $super['name']; // 分公司
                           $super['identity'] == 4 && $market_partner .= $super['name'] && $branch_company .= " ". $super['corporate_name']; // 市场合伙人
                       }

                   }

                }
                if ($item['parent_identity'] == 4) { // 上级为市场合伙人
                    $market_partner .= $item['parent_name']; // 市场合伙人名称
                    $branch_company .= $parent_agent_corporate[$item['inviter_id']]; // 分公司名称

                    $location = $this->location_dao->getLocationByPid([
                        'pid' => $item['location_id'],
                    ]);
                    $location ?$location->toArray:[];
                    $up_city_agent = $this->agent_dao->map([
                        'location_id' => $location['level'],
                        'identity' => 2
                    ]);
                    if ($up_city_agent) { // 上层市代存在
                        $up_city_agent = $up_city_agent->toArray();
                        $city_agent .= $up_city_agent['name']; // 市代理名称

                        $super = $this->agent_dao->map([
                            'id' => $up_city_agent['inviter_id'],
                        ],false); // 最后一步，最高一层 合伙人或者分公司

                        if ($super && $super = $super->toArray() && $super['id'] != $item['inviter_id'] ) { // 市代存在且市代的邀请人存在

                            $super['identity'] == 3 && $branch_company .= " ". $super['name']; // 分公司
                            $super['identity'] == 4 && $market_partner .= " " .$super['name'] && $branch_company .= " ". $super['corporate_name']; // 市场合伙人
                        }

                    }
                }
            } elseif ($item['identity'] == 2) { // 如果是市代理身份
                if ($item['parent_identity'] == 4) {
                    $market_partner .= $item['parent_name']; // 市场合伙人名称
                    $branch_company .= $parent_agent_corporate[$item['inviter_id']]; // 分公司名称
                } elseif ($item['parent_identity'] == 3) {
                    $branch_company .= $item['parent_name']; // 分公司名称
                }
            }

            $item['city_agent'] = $city_agent; // 市代理
            $item['market_partner'] = $market_partner; // 市场合伙人
            $item['branch_company'] = $branch_company; // 分公司
        }

        return $agent_list;
    }

    /**
     * 获得渠道商搜索结果
     * @param array $params
     * @return mixed
     */
    public function getChannelSearch(array $params)
    {
        $map = [];
        isset($params['start_time']) && !isset($params['end_time']) && !empty($params['start_time']) && $map['created_at'] = ['>=', strtotime($params['start_time'])]; // 申请开始时间
        isset($params['end_time']) &&  !isset($params['start_time'])&& !empty($params['end_time'])  && $map['created_at'] = ['<=', strtotime($params['end_time'])]; // 申请结束时间

        isset($params['end_time']) &&  isset($params['start_time'])
        && !empty($params['end_time']) && !empty($params['start_time'])
        && $map['between_field'] = ['created_at' =>[strtotime($params['start_time']), strtotime($params['end_time'])]]; // 有申请开始和结束时间

        isset($params['parent_id']) && !empty($params['parent_id']) && $map['parent_id'] = (int)$params['parent_id']; // 上级渠道商ID

        isset($params['name'])  && !empty($params['name']) && $map['name'] = ['like', "%{$params['name']}%"]; // 姓名
        isset($params['phone'])  && !empty($params['phone']) && $map['phone'] = ['like', "%{$params['phone']}%"]; // 账号

        isset($params['identity_code'])  && !empty($params['identity_code']) && $map['identity_code'] = ['like', "%{$params['identity_code']}%"]; // 邀请码

        isset($params['province_id']) && $map['province_id'] = (int)$params['province_id'];//省
        isset($params['city_id']) && !empty($params['city_id']) && $map['city_id'] = (int)$params['city_id'];//市
        isset($params['district_id']) && !empty($params['district_id']) && $map['district_id'] = (int)$params['district_id'];//区

        // 市场合伙人或者分公司的代理商ID，直招的区所有渠道商
        if (isset($params['agent_id']) && !empty($params['agent_id'])) {
            $district_agents = $this->agent_dao->getAgentsByMap([
                'inviter_id' => (int)$params['agent_id'],
                'identity' => 1, // 区代
            ], null, ['location_id'])->toArray();

            $district_ids = array_unique(array_column($district_agents, 'location_id'));

            $map['district_id'] = ['in', $district_ids];
        }

        $map['group_id'] = 2; // 渠道商
        $sort = 'created_at desc';
        $select = ['id', 'name', 'province', 'province_id', 'city', 'city_id', 'district', 'district_id', 'phone', 'identity_code', 'created_at', 'status'];

        $page_size = 10;

        $channel_list = $this->user_dao->getUsersByMap($map, $sort, $select, $page_size)->toArray();

        $channel_list['data'] = $this->joinChannelData($channel_list['data']);

        return $channel_list;
    }

    /**
     *  渠道商数据加入
     * @param array $channel_list
     * @return mixed
     */
    public function joinChannelData(array $channel_list)
    {
        $city_ids = array_unique(array_column($channel_list, 'city_id'));

        $district_ids = array_unique(array_column($channel_list, 'district_id'));

        $area_ids = array_merge($city_ids, $district_ids);

        $agents = $this->agent_dao->getAgentsByMap([
            'location_id' => ['in', $area_ids],
            'identity' => ['in',[1, 2]], // 市代，区代
        ], null, ['name', 'location_id', 'identity', 'inviter_id']);

        $agent_array = $agents->toArray();

        $inviter_ids = array_unique(array_column($agent_array, 'inviter_id')); // 获得所有区代市代的上级ID

        $area_names = $agents->pluck('name', 'location_id')->toArray(); // 区代 市代（第一层上级）

        $area_partners = $agents->pluck('inviter_id', 'location_id')->toArray(); // 合伙人或者分公司或者市代（第二层上级）

        $supers = $this->agent_dao->getAgentsByMap([
            'id' => ['in', $inviter_ids],
        ], null, ['name', 'identity', 'id'])->groupBy('id')->toArray(); // 所有


        foreach ($channel_list as &$item) {
            $item['district_agent'] = $area_names[$item['district_id']]??''; // 所属区代理（第一层上级）
            $item['city_agent'] = $area_names[$item['city_id']]??''; // 所属市代理（第一层上级）
            $market_partner = ""; // 市场合伙人
            $branch_company = ""; // 分公司
            $district_inviter_id = $area_partners[$item['district_id']]??null; // 区代的推荐者的ID
            $city_inviter_id = $area_partners[$item['city_id']]??null; // 市代的推荐者ID

            if ($district_inviter_id && isset($supers[$district_inviter_id])) { // 是否存在区代的上级推荐者
                $district_super = $supers[$district_inviter_id];
                foreach ($district_super as $super_item) {
                    $super_item['identity'] == 3 && $branch_company .= $super_item['name']." "; // 区代的上级推荐者为 分公司
                    $super_item['identity'] == 4 && $market_partner .= $super_item['name']." "; // 区代的上级推荐者为 市场合伙人
                }

            }

            if ($city_inviter_id && $district_inviter_id != $city_inviter_id && isset($supers[$city_inviter_id])) { // 是否存在市代的上级推荐者 （和区代同一个的话就不重复了）
                $city_super = $supers[$city_inviter_id];

                foreach ($city_super as $city_super_item) {
                    $city_super_item['identity'] == 3 && $branch_company .= $city_super_item['name']." "; // 市代的上级推荐者为 分公司
                    $city_super_item['identity'] == 4 && $market_partner .= $city_super_item['name']." "; // 市代的上级推荐者为 市场合伙人

                }

            }

            $item['market_partner'] = $market_partner; // 市场合伙人
            $item['branch_company'] = $branch_company; // 分公司
            $item['status_text'] = $item['status'] == 1?"正常":"禁用"; // 状态名称
            $item['create_time'] = date("Y.m.d",(int)$item['created_at']); // 创建时间
        }

        return $channel_list;

    }

    /**
     * 创建代理
     * @param array $params
     */
    public function createAgent(array $params)
    {
        $data = [];
        // 账户信息
        $data['identity'] = (int)$params['identity']; // 代理商角色 1区代/2市代/3分公司/4合伙人
        $data['name'] = $params['name']; // 代理商名称
        $data['phone'] = $params['phone']; // 手机号码/登录账号
        $data['login_pwd'] = password_hash($params['phone'],PASSWORD_DEFAULT); // 手机号码/登录账号
        $phone = $this->agent_dao->getAgentByPhone($params['phone'], ['id', 'phone']);
        $phone && $this->error("该手机号用户已存在");
        $data['link_phone'] = $params['link_phone']; // 联系方式
        $data['address'] = $params['address']; // 现住地址/联系地址
        $data['contact_name'] = $params['contact_name']; // 联系人

        // 认证资料（必填）
        $data['settle_name'] = $params['settle_name']; // 法人姓名
        $data['sex'] = (int)$params['sex']; // 性别：1-男 2-女
        $data['settle_idcard_no'] = $params['settle_idcard_no']; // 法人身份证号
        $data['settle_idcard_front'] = $params['settle_idcard_front']; // 法人身份证正面
        $data['settle_idcard_back'] = $params['settle_idcard_back']; // 法人身份证反面

        $data['settle_bank_username'] = $params['settle_bank_username']; // 结算人姓名
        $data['settle_bank'] = $params['settle_bank']; // 结算人开户行
        $data['settle_bank_account'] = $params['settle_bank_account']; // 结算人银行账号
        $data['settle_bank_front'] = $params['settle_bank_front']; // 结算人银行卡照片
        $data['bank_branch'] = $params['bank_branch']; // 银行支行名称

        // 认证资料（选填）
        isset($params['corporate_name']) && !empty($params['corporate_name']) && $data['corporate_name'] = $params['corporate_name']; // 公司名称
        isset($params['business_license']) && !empty($params['business_license']) && $data['business_license'] = $params['business_license']; // 营业执照

        // 备注信息
        isset($params['sales_man']) && !empty($params['sales_man']) && $data['sales_man'] = $params['sales_man']; // 业务员


        if( isset($params['inviter_id']) && !empty($params['inviter_id']) ) { // 邀请人ID
            $agent = $this->agent_dao->first($params['inviter_id']);
            !$agent && $this->error("AGENT.NOT_EXIT");

            $params['identity'] == 1 && $agent->identity == 1 && $this->error("区代理不能推荐区代理");

            $params['identity'] == 2 && in_array($agent->identity, [1, 2]) && $this->error("市代理区代理不能推荐市代理");

            $params['identity'] == 4 && in_array($agent->identity, [1, 2, 4]) && $this->error("市场合伙人只能是分公司推荐");

            $params['identity'] == 3 && in_array($agent->identity, [1, 2,3, 4]) && $this->error("分公司不能被区代理市代理市场合伙人推荐");

            $data['inviter_id'] = (int)$params['inviter_id']; // 邀请人ID
        }

        if (isset($params['location_id']) && !empty($params['location_id']) ) { // 区域选择
            $level_first = $this->location_dao->getLocationByPid([
                'pid' => $params['location_id'],
            ]);
            !$level_first && $this->error("代理区域不在选择范围之内");
            if ($params['identity'] == 1 || $params['identity'] == 2) { // 查看市代或者区代是否存在
                $location = $this->agent_dao->map([
                    'location_id' => $params['location_id'],
                    'identity' => ['in', [1, 2]],
                ], false);
                $location && $this->error("该地区已经存在市代或者区代");

            }

            $level_first = $level_first->toArray();
            $level = $level_first['level'];

            $params['identity'] == 1 && $level != 0 && $level % 1000 == 0 && $this->error("区代理不能代理市");
            $params['identity'] == 2 && $level % 1000 != 0 && $this->error("市代理不能代理区");

            $data['location_id'] = (int)$params['location_id']; // 代理区域
        }

        // 分润设置

        if (isset($params['area_agent_money']) && !empty($params['area_agent_money'])) {
            $params['area_agent_money'] > 0.041 && $this->error("金额返佣超过数值");
            $data['area_agent_money'] = (float)$params['area_agent_money']; // 区代理金额返佣
        }
        if ( isset($params['city_agent_money']) && !empty($params['city_agent_money']) )  {
            $params['city_agent_money'] > 0.041 && $this->error("金额返佣超过数值");

            $data['city_agent_money'] = (float)$params['city_agent_money']; // 市代理金额返佣
        }

        if ( isset($params['channel_agent_money']) && !empty($params['channel_agent_money']) ) {
            $params['channel_agent_money'] > 0.6 && $this->error("渠道商返佣超过数值");
            $data['channel_agent_money'] = (float)$params['channel_agent_money']; // 渠道商金额返佣
        }
        $data['status'] = 1; // 已审核状态
        $result = $this->agent_dao->create($data);
        !$result && $this->error("AGENT.CREATE_FAIL");
    }

    /**
     * 渠道商详情
     * @param int $id
     * @return mixed
     */
    public function channelDetail(int $id)
    {
        $first = $this->user_dao->first($id);
        !$first && $this->error("该渠道商不存在");
        $first = $first->makeHidden(['login_pwd', 'safe_pwd'])->toArray();
        $city_agent_name = ''; // 所属市代
        $district_agent_name = ''; // 所属区代
        $market_partner = ''; // 所属市场合伙人
        $branch_company = '';
        // 市代
        $city_agent = $this->agent_dao->map([
            'location_id' => $first['city_id'],
            'identity' => 2,
        ], false);
        // 如果市代存在
        if ($city_agent) {
            $city_agent = $city_agent->toArray();
            $city_agent_name .= $city_agent['name'];

            $city_parent = $this->agent_dao->map([
                'id' => $city_agent['inviter_id'],
                'identity' => ['in', [3,4]],
            ], false); // 合伙人或者分公司
            if ($city_parent) {
                $city_parent = $city_parent->toArray();
                $city_parent['identity'] == 3 && $branch_company .= ' '.$city_parent['name']. ' '; // 分公司
                $city_parent['identity'] == 4 && $market_partner .= ' '.$city_parent['name']. ' ' && $branch_company .= ' '.$city_parent['corporate_name']. ' '; // 合伙人
            }


        }
        // 如果区代存在
        $district_agent = $this->agent_dao->map([
            'location_id' => $first['district_id'],
            'identity' => 1,
        ], false);

        if ($district_agent) {
            $district_agent = $district_agent->toArray();
            $district_agent_name .= $district_agent['name'];

            $district_parent = $this->agent_dao->map([
               'id' => $district_agent['inviter_id'],
               'identity' => ['in', [3,4]],
            ], false);
            if ($district_parent) {
                $district_parent = $district_parent->toArray();
                if ($district_agent['inviter_id'] != $city_agent['inviter_id'] ) { // 区代理和市代理不同的邀请人
                    $district_parent['identity'] == 3 && $branch_company .=  ' '.$district_parent['name']. ' '; // 分公司
                    $district_parent['identity'] == 4 && $market_partner .=  ' '.$district_parent['name']. ' ' && $branch_company .= ' '.$district_parent['corporate_name']. ' '; // 合伙人

                }

            }

        }

        $first['city_agent'] = $city_agent_name; // 所属市代
        $first['district_agent'] = $district_agent_name; // 所属区代
        $first['market_partner'] = $market_partner; // 市场合伙人
        $first['branch_company'] = $branch_company; // 分公司
        return $first;
    }

    /**
     * 获取合作商的商家信息
     * @param array $params
     * @return mixed
     */
    public function getBusinessList(array $params)
    {
        $map = [];
        isset($params['parent_id']) && !empty($params['parent_id']) && $map['parent_id'] = $params['parent_id']; // 上级ID
        isset($params['city_id']) && !empty($params['city_id']) && $map['city_id'] = $params['city_id']; // 市级ID
        isset($params['district_id']) && !empty($params['district_id']) && $map['district_id'] = $params['district_id']; // 区/县ID

        $sort = 'created_at desc';
        $select = ['id', 'created_at', 'name', 'phone', 'tel', 'user_id', 'address', 'legal_name', 'city_id', 'city', 'district_id', 'district', 'status'];
        $page_size = 10;

        $business_list = $this->business_dao->getBusinessByMap($map, $sort, $select, $page_size)->toArray();

        $business_list['data'] = $this->joinBusinessData($business_list['data']);

        return $business_list;

    }

    /**
     * 商家数据拼接
     * @param array $business_list
     * @return array
     */
    public function joinBusinessData(array $business_list)
    {
        $city_ids = array_unique(array_column($business_list, 'city_id')); // 市ID

        $district_ids = array_unique(array_column($business_list, 'district_id')); // 区ID

        $area_ids = array_merge($city_ids, $district_ids);

        $user_ids = array_column($business_list, 'user_id');

        // 账号
        $user_phones = $this->user_dao->getUsersByIdsNotGroup($user_ids, ['id', 'phone'])->pluck('phone', 'id')->toArray();

        // 所在地的代理商名称
        $location_names = $this->agent_dao->getAgentsByMap([
            'location_id' => ['in', $area_ids], // 所在地区
            'identity' => ['in', [1,2]], // 市代和区代
        ], null, ['location_id', 'name'])->pluck('name', 'location_id')->toArray();

        foreach ($business_list as &$item) {
            $item['city_agent_name'] = $location_names[$item['city_id']]??""; // 所属市代
            $item['district_agent_name'] = $location_names[$item['district_id']]??""; // 所属区代
            $item['account'] = $user_phones[$item['user_id']]??""; // 账号
        }

        return $business_list;

    }


    
}